﻿using Asmodat.Abbreviate;
using Asmodat.Extensions;
using Asmodat.Extensions.Collections.Generic;
using Asmodat.Extensions.Objects;
using Asmodat.IO;
using Asmodat.Types;
using AsmodatMath;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Asmodat_ELM
{
    public partial class Form1 : Form
    {
        private void TBtnUpload_OnClick(object source, Asmodat.FormsControls.ThreadedTwoStateButtonClickStatesEventArgs e)
        {
            if (e.On)
            {
                this.Upload_Start();
            }
            else
            {
                this.Upload_Stop();
            }

            //TBtnUpload.Switch();
        }

       

        public void Upload_Start()
        {
            this.Info = "Upload Started.";
            Methods.Run(() => Upload(), null, true, true);
            TBtnUpload.SwitchOff();
            SettingsEnabled = false;
            DeviceColor = Color.DarkBlue;
        }

        public void Upload_Stop()
        {
            Methods.Terminate(() => Upload());
            if (_serialPort.Started)
            {
                TTbxSubmit.Enabled = true;
                TBtnSend.Enabled = true;
            }
            Uploading = false;
            TBtnUpload.SwitchOn();
            this.Info = "Upload failed - Terminated.";
            SettingsEnabled = true;
            DeviceColor = Color.DarkRed;
        }

        public int upload_timeout { get { return TTbxUploadTimeout.Text.ParseInteger(10000); } }
        public bool Uploading { get; private set; } = false;

        public void Upload()
        {
            TTbxSubmit.Enabled = false;
            TBtnSend.Enabled = false;
            Uploading = true;

            var files = TCLBxFiles.GetItems<string>(true);

            //lc lua
            var files_end = files.Where(f => f.ToLower() == "init.lua" || f.ToLower() == "init.lc").ToList();

            if (!files_end.IsNullOrEmpty())
            {
                files.RemoveRange(files_end);
                files.AddRange(files_end);
            }

            int timeout = upload_timeout;

            int success_count = 0;
            for(int i = 0; i < files.Count; i++)
            {
                
                string file = files[i];

                this.Info = string.Format("Uploading... {0}/{1} - {2}", i+1, files.Count, file);

                if (!Files.Exists(file) || !_serialPort.IsOpen)
                    continue;

                Thread.Sleep(100);
                TickTime time = TickTime.Now;
                List<string> result = Files.ReadAllLines(file);

                if (!this.SendSync(string.Format("file.remove(\"{0}\");", file))) continue;
                if (!this.SendSync(string.Format("file.open(\"{0}\",\"w+\");", file))) continue;

                if (result.IsNullOrEmpty())
                    continue;

                if (!this.SendSync(string.Format("w = file.writeline"))) continue;

                bool success = true;
                foreach (string line in result)
                {
                    string text = line.TryTrim(new char[] { ' ', '\n', '\t', '\r' });

                    if (text.IsNullOrWhiteSpace())
                        text = "";

                    if (!(success = this.SendSync(string.Format("w([==[{0}]==]);", text))))
                        break;
                }

                if (!success)
                    continue;

                if (!this.SendSync("file.close();")) continue;
                if (!this.SendSync(string.Format("dofile(\"{0}\");", file))) continue;

                if (success)
                    UploadedFiles[file] = time;

                ++success_count;
            }

            if (files.IsNullOrEmpty())
                this.Info = "Upload failed - no files to upload.";
            else
                this.Info = string.Format("Upload compleated, success ratio: {0}/{1}", success_count, files.Count);

            Uploading = false;
            TBtnUpload.Switch();
            DeviceColor = Color.DarkRed;
            SettingsEnabled = true;

            if (_serialPort.Started)
            {
                TTbxSubmit.Enabled = true;
                TBtnSend.Enabled = true;
            }
            Uploading = false;
        }

    }
}
